package com.squirrel.serialportcore.machine.init.before;

import com.alibaba.fastjson.JSON;
import com.squirrel.serialportcore.common.CommonBase;
import com.squirrel.serialportcore.entity.property.JsonProperty;
import com.squirrel.serialportcore.exception.CoreException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * Json文件读取配置
 *
 * @author Squbi
 * @date 2021/3/23 10:47
 */
public class JsonReader {
    private static final Logger logger = LoggerFactory.getLogger(JsonReader.class);

    private JsonReader() {
    }

    public static void read() {
        String classPath = Objects.requireNonNull(JsonReader.class.getClassLoader().getResource("")).getPath();
        logger.debug(" -debug- CLASS_PATH {}", classPath);
        if (classPath.startsWith("file:")) {
            classPath = classPath.substring(5);
        }
        String path = classPath.substring(1, classPath.indexOf("serial-port-core")) + "spc.json";
        logger.debug(" -debug- FILE_PATH {}", path);
        File file = new File(path);
        if (!file.exists() || file.isDirectory()) {
            throw new CoreException(logger, " 配置文件不存在 请在当前目录下进行创建 spc.json");
        }
        try (Reader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) {
            int read;
            StringBuilder stringBuilder = new StringBuilder();
            while ((read = reader.read()) > 0) {
                stringBuilder.append((char) read);
            }
            String json = stringBuilder.toString();
            JsonProperty jsonProperty = JSON.parseObject(json, JsonProperty.class);
            CommonBase.setJsonProperty(jsonProperty);
            logger.debug(" -debug- JsonProperty初始化完成 \n -> {}", jsonProperty);
        } catch (Exception e) {
            throw new CoreException(logger, e, " spc.json配置文件读取异常 路径 {} 原因 {}", path, e.getMessage());
        }
    }
}
